import React from "react";
import { FieldValues, useForm } from "react-hook-form";

// 需要导入依赖  npm i react-hook-form

interface FormData {
  username: string;
  password: string;
}

const HookForm = () => {
  const {
    register,
    handleSubmit,
    formState: { errors }, // 结构formState中的错误数据
  } = useForm<FormData>();

  console.log(errors);

  const onSubmit = (data: FieldValues) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div className="mb-3">
        <label htmlFor="username" className="form-label">
          账号
        </label>
        <input
          id="username"
          type="text"
          {...(register("username"), { required: true, minLength: 5 })}
          className="form-control"
        />
        {/* username可能为空所以需要？ */}
        {errors.username?.type === "required" && (
          <p className="alert alert-danger">此选项必填</p>
        )}
        {errors.username?.type === "minLength" && (
          <p className="alert alert-danger">此选项最小长度需要大于5</p>
        )}
      </div>
      <div className="mb-3">
        <label htmlFor="password" className="form-label">
          密码
        </label>
        <input
          id="password"
          type="password"
          {...register("password")}
          className="form-control"
        />
      </div>
      <button className="btn btn-secondary">登录</button>
    </form>
  );
};

export default HookForm;
